<?php
namespace app\common\model;


use think\Cache;

class Cate extends CommonModel
{
    public function cate(){
        return $this->belongsTo('Cate', 'pid', 'id',  [], 'LEFT')->field('cate_name');
    }

    /**
     * 父类选择列表
     * @desc 父类选择列表
     */
    public function getParentCateList(){
        return $this->where(['pid'=>0])->select();
    }

    /**
     * 分类选择列表
     * @desc 分类选择
     */
    public function getCateChoicesList(){
        if(Cache::has('cate_choices_list')){
            return Cache::get('cate_choices_list');
        }else{
            $result = $this->where([/*'id'=>['<>',1]*/])->select();
            if($result){
                $result = $this->generatorList($result->toArray(),0);
                if($result){
                    Cache::set('cate_choices_list',$result);
                }
                return $result;
            }else{
                return [];
            }
        }
    }

    /**
     * 无限递归分类
     * @desc 无限递归分类
     */
    private function generatorList($list,$pid,$space = '--'){
        $newList = [];
        foreach ($list as $k => $v){
            if($v['pid'] == $pid){
                $v['cate_name'] = $space.'  '.$v['cate_name'];
                $newList[] = $v;
                $result = $this->generatorList($list,$v['id'],$space.'----');
                if(!empty($result)){
                    $newList = array_merge($newList,$result);
                }
            }
        }
        return $newList;
    }

    /**
     * 无限递归分类2
     * @param $list
     * @param $pid
     * @return array
     */
    private function generatorHomeList($list,$pid){
        $newList = [];
        foreach ($list as $k => $v){
            if($v['pid'] == $pid){
                $result = $this->generatorHomeList($list,$v['id']);
                if(!empty($result)){
                    $v['children'] = $result;
                }
                $newList[] = $v;
            }
        }
        return $newList;
    }
    
    /**
     * 获取分类列表
     * @desc 获取分类列表 
     */
    public function getHomeCateList(){
        if(Cache::has('cate_home_choices_list')){
            return Cache::get('cate_home_choices_list');
        }else{
            $result = $this->where(['id'=>['<>',1]])->select();
            if($result){
                $result = $this->generatorHomeList($result->toArray(),0);

                if($result){
                    Cache::set('cate_home_choices_list',$result);
                }
                return $result;
            }else{
                return [];
            }
        }
    }
}